{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.signal import convolve2d\n",
    "import math\n",
    "class ContinuousCellularAutomata:\n",
    "    def __init__(self, size, kernel, rule_func, initial_state=None):\n",
    "        \"\"\"\n",
    "        初始化连续性元胞自动机。\n",
    "\n",
    "        参数:\n",
    "        - size: 元胞网格的大小 (height, width)。\n",
    "        - kernel: 卷积核，用于计算邻居的影响。\n",
    "        - rule_func: 生成函数，用于更新元胞状态。\n",
    "        - initial_state: 初始状态矩阵，如果为 None，则随机初始化。\n",
    "        \"\"\"\n",
    "        self.size = size\n",
    "        self.kernel = kernel\n",
    "        self.rule_func = rule_func\n",
    "        self.state = initial_state if initial_state is not None else np.random.rand(*size)\n",
    "\n",
    "    def update(self,dt=1):\n",
    "        \"\"\"更新元胞自动机的状态。\"\"\"\n",
    "        # 计算邻居的影响\n",
    "        neighbor_effect = convolve2d(self.state, self.kernel, mode='same', boundary='wrap')\n",
    "        # 应用生成函数更新状态\n",
    "        self.state += dt*(self.rule_func(self.state, neighbor_effect)-self.state)\n",
    "\n",
    "    def simulate(self, steps, plot_interval=1,dt=1):\n",
    "        \"\"\"模拟元胞自动机并可视化。\n",
    "\n",
    "        参数:\n",
    "        - steps: 模拟步数。\n",
    "        - plot_interval: 每隔多少步绘制一次状态。\n",
    "        \"\"\"\n",
    "       \n",
    "        for step in range(steps):\n",
    "            if step % plot_interval == 0:\n",
    "                plt.figure(figsize=(10, 10))\n",
    "                plt.imshow(self.state, cmap='viridis',vmin=0, vmax=1)#\n",
    "                #plt.colorbar(label='State Value')\n",
    "                plt.title(f\"Step {step}\")\n",
    "                plt.savefig(r\"D:\\3_bodies\\live_game\\cca_\"+str(step)+\".jpg\")\n",
    "                plt.show()\n",
    "            self.update(dt=dt)\n",
    "            \n",
    "\n",
    "\n",
    "# 示例生成函数\n",
    "def example_rule(state, neighbor_effect):\n",
    "    \"\"\"示例生成函数：基于邻居影响更新状态。\"\"\"\n",
    "    return np.clip(state + 0.1 * neighbor_effect, 0, 1)\n",
    "def gol_rule(s, n):\n",
    "    output=np.zeros(n.shape)\n",
    "    print(output.shape)\n",
    "    for i in range(len(n)):\n",
    "        for j in range(len(n[i])):\n",
    "            if n[i,j]<0.25:\n",
    "                output[i,j]=(1/(1+math.e**(-100*(n[i,j]+0.1*s[i,j]-0.23))))\n",
    "            else:\n",
    "                output[i,j]=(1/(1+math.e**(-100*(0.32-n[i,j]))))\n",
    "    return output\n",
    "# 示例卷积核\n",
    "example_kernel = np.array([\n",
    "    [0, 0.1, 0],\n",
    "    [0.1, 0, 0.1],\n",
    "    [0,0.1, 0]\n",
    "])\n",
    "example_kernel_2 = np.array([\n",
    "    [0.05, 0.9, 0.05],\n",
    "    [0.9, 1, 0.9],\n",
    "    [0.05,0.9, 0.05]\n",
    "])\n",
    "example_kernel_m = np.array([\n",
    "    [0.5, 0.9, 0.5],\n",
    "    [0.9, 1, 0.9],\n",
    "    [0.5,0.9, 0.5]\n",
    "])\n",
    "example_kernel = np.array([\n",
    "    [0,0.025, 0.025, 0.025,0],\n",
    "    [0.025,0.05, 0.1, 0.05,0.025],\n",
    "    [0.025,0.1, 0, 0.1,0.025],\n",
    "    [0.025,0.05, 0.1, 0.05,0.025],\n",
    "    [0,0.025,0.025, 0.025,0]\n",
    "])\n",
    "x = np.linspace(0, 2, 100).reshape(2,50)\n",
    "\n",
    "print(x.shape)\n",
    "s=np.ones(x.shape)\n",
    "y=gol_rule(s,x)\n",
    "plt.plot(x[0], y[0], label=\"Rule(x)\")\n",
    "plt.title(\"Rule Function\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"rule(x)\")\n",
    "plt.grid(True)\n",
    "plt.legend()\n",
    "plt.show()\n",
    "# 运行示例\n",
    "if __name__ == \"__main__\":\n",
    "    # 初始化元胞自动机\n",
    "    size = (100, 100)  # 网格大小\n",
    "    cca = ContinuousCellularAutomata(size, example_kernel, gol_rule)\n",
    "\n",
    "    # 模拟并可视化\n",
    "    cca.simulate(steps=1000, plot_interval=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "#imgs2video\n",
    "import os\n",
    "import cv2\n",
    "from PIL import Image\n",
    "fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') \n",
    "path=r\"D:\\3_bodies\\live_game\\cca_\"#input(\"path?\")\n",
    "save_path=r\"D:/3_bodies/cca_27.mp4\"#input(\"save_path?\")\n",
    "post_video=cv2.VideoWriter(save_path, fourcc, 30,(720,720))\n",
    "len_img=999\n",
    "for i in range(len_img+1):\n",
    "    print(path+str(i)+\".jpg\")\n",
    "    img=cv2.imread(path+str(i)+\".jpg\")\n",
    "    post_video.write(img)\n",
    "    if i==len_img:\n",
    "        for t in range(100):\n",
    "            post_video.write(img)\n",
    "    del img\n",
    "    #if filename==\"0.jpg\":\n",
    "        #Image.fromarray(img).show()\n",
    "\n",
    "post_video.release()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "example_kernel = np.array([\n",
    "    [0,0.025, 0.025, 0.025,0],\n",
    "    [0.025,0.1, 0.1, 0.1,0.025],\n",
    "    [0.025,0.1, 0, 0.1,0.025],\n",
    "    [0.025,0.1, 0.1, 0.1,0.025],\n",
    "    [0,0.025,0.025, 0.025,0]\n",
    "])\n",
    "def gol_rule(s, n):\n",
    "    output=np.zeros(n.shape)\n",
    "    print(output.shape)\n",
    "    for i in range(len(n)):\n",
    "        for j in range(len(n[i])):\n",
    "            if n[i,j]<0.25:\n",
    "                output[i,j]=(1/(1+math.e**(-100*(n[i,j]+0.1*s[i,j]-0.27))))\n",
    "            else:\n",
    "                output[i,j]=(1/(1+math.e**(-100*(0.32-n[i,j]))))\n",
    "    return output\n",
    "x = np.linspace(0, 2, 100).reshape(2,50)\n",
    "print(x.shape)\n",
    "s=np.ones(x.shape)\n",
    "y=gol_rule(s,x)\n",
    "plt.plot(x[0], y[0], label=\"Rule(x)\")\n",
    "plt.title(\"Rule Function\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"rule(x)\")\n",
    "plt.grid(True)\n",
    "plt.legend()\n",
    "plt.show()\n",
    "size = (100, 100)  # 网格大小\n",
    "cca = ContinuousCellularAutomata(size, example_kernel, gol_rule)\n",
    "    # 模拟并可视化\n",
    "cca.simulate(steps=1000, plot_interval=1,dt=0.8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import poisson\n",
    "example_kernel = np.ones([10,10])*0.0035\n",
    "#for i in range(len(example_kernel)):\n",
    "    #for j in range(len(example_kernel[i])):\n",
    "        #example_kernel=\n",
    "def gol_rule(s, n):\n",
    "    output=np.zeros(n.shape)\n",
    "    print(output.shape)\n",
    "    for i in range(len(n)):\n",
    "        for j in range(len(n[i])):\n",
    "            if n[i,j]<0.25:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.175))))\n",
    "            elif n[i,j]<0.5:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.62-n[i,j]))))\n",
    "            elif n[i,j]<0.7:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.32))))\n",
    "            else:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.82-n[i,j]))))\n",
    "            \n",
    "            \n",
    "    return output\n",
    "x = np.linspace(0, 2, 100).reshape(2,50)\n",
    "print(x.shape)\n",
    "s=np.ones(x.shape)\n",
    "y=gol_rule(s,x)\n",
    "plt.plot(x[0], y[0], label=\"Rule(x)\")\n",
    "plt.title(\"Rule Function\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"rule(x)\")\n",
    "plt.grid(True)\n",
    "plt.legend()\n",
    "plt.show()\n",
    "size = (100, 100)  # 网格大小\n",
    "cca = ContinuousCellularAutomata(size, example_kernel, gol_rule)\n",
    "    # 模拟并可视化\n",
    "cca.simulate(steps=1000, plot_interval=1,dt=0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "from scipy.stats import poisson\n",
    "k_l=33\n",
    "example_kernel = np.zeros([k_l,k_l])\n",
    "for i in range(len(example_kernel)):\n",
    "    for j in range(len(example_kernel[i])):\n",
    "        if -4<int(k_l/2)**2-(i-int(k_l/2))**2-(j-int(k_l/2))**2<49:\n",
    "            example_kernel[i,j]=1\n",
    "    print(example_kernel[i])\n",
    "example_kernel*=0.0008\n",
    "def gol_rule(s, n):\n",
    "    output=np.zeros(n.shape)\n",
    "    #print(output.shape)\n",
    "    for i in range(len(n)):\n",
    "        for j in range(len(n[i])):\n",
    "            if n[i,j]<0.3:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.22))))\n",
    "            else:#elif n[i,j]<0.5:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.38-n[i,j]))))\n",
    "            #elif n[i,j]<0.7:\n",
    "                #output[i,j]=(1/(1+math.e**(-100*(n[i,j]-0.62))))\n",
    "            #else:\n",
    "                #output[i,j]=(1/(1+math.e**(-100*(0.78-n[i,j]))))\n",
    "            \n",
    "            \n",
    "    return output\n",
    "x = np.linspace(0, 2, 100).reshape(2,50)\n",
    "print(x.shape)\n",
    "s=np.ones(x.shape)\n",
    "y=gol_rule(s,x)\n",
    "plt.plot(x[0], y[0], label=\"Rule(x)\")\n",
    "plt.title(\"Rule Function\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"rule(x)\")\n",
    "plt.grid(True)\n",
    "plt.legend()\n",
    "plt.show()\n",
    "size = (100, 100)  # 网格大小\n",
    "cca = ContinuousCellularAutomata(size, example_kernel, gol_rule)\n",
    "    # 模拟并可视化\n",
    "cca.simulate(steps=1000, plot_interval=1,dt=0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import poisson\n",
    "k_l=33\n",
    "example_kernel = np.zeros([k_l,k_l])\n",
    "for i in range(len(example_kernel)):\n",
    "    for j in range(len(example_kernel[i])):\n",
    "        if -4<int(k_l/2)**2-(i-int(k_l/2))**2-(j-int(k_l/2))**2<49:\n",
    "            example_kernel[i,j]=1#1/(1+((i-int(k_l/2))**2+(j-int(k_l/2))**2))\n",
    "    print(example_kernel[i])\n",
    "example_kernel*=0.009\n",
    "def gol_rule(s, n):\n",
    "    output=np.zeros(n.shape)\n",
    "    #print(output.shape)\n",
    "    for i in range(len(n)):\n",
    "        for j in range(len(n[i])):\n",
    "            if n[i,j]<0.25:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.16))))\n",
    "            elif n[i,j]<0.5:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.32-n[i,j]))))\n",
    "            elif n[i,j]<0.75:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.65))))\n",
    "            else:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.82-n[i,j]))))\n",
    "            \n",
    "            \n",
    "    return output\n",
    "x = np.linspace(0, 2, 100).reshape(2,50)\n",
    "print(x.shape)\n",
    "s=np.ones(x.shape)\n",
    "y=gol_rule(s,x)\n",
    "plt.plot(x[0], y[0], label=\"Rule(x)\")\n",
    "plt.title(\"Rule Function\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"rule(x)\")\n",
    "plt.grid(True)\n",
    "plt.legend()\n",
    "plt.show()\n",
    "size = (100, 100)  # 网格大小\n",
    "cca = ContinuousCellularAutomata(size, example_kernel, gol_rule)\n",
    "    # 模拟并可视化\n",
    "cca.simulate(steps=1000, plot_interval=1,dt=0.1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import poisson\n",
    "k_l=33\n",
    "example_kernel = np.zeros([k_l,k_l])\n",
    "for i in range(len(example_kernel)):\n",
    "    for j in range(len(example_kernel[i])):\n",
    "        if -4<int(k_l/2)**2-(i-int(k_l/2))**2-(j-int(k_l/2))**2<49:\n",
    "            example_kernel[i,j]=1#1/(1+((i-int(k_l/2))**2+(j-int(k_l/2))**2))\n",
    "    print(example_kernel[i])\n",
    "example_kernel*=0.009\n",
    "def gol_rule(s, n):\n",
    "    output=np.zeros(n.shape)\n",
    "    #print(output.shape)\n",
    "    for i in range(len(n)):\n",
    "        for j in range(len(n[i])):\n",
    "            if n[i,j]<0.25:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.16))))\n",
    "            elif n[i,j]<0.5:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.32-n[i,j]))))\n",
    "            elif n[i,j]<0.75:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(n[i,j]-0.65))))\n",
    "            else:\n",
    "                output[i,j]=(1/(1+math.e**(-50*(0.82-n[i,j]))))\n",
    "            \n",
    "            \n",
    "    return output\n",
    "x = np.linspace(0, 2, 100).reshape(2,50)\n",
    "print(x.shape)\n",
    "s=np.ones(x.shape)\n",
    "y=gol_rule(s,x)\n",
    "plt.plot(x[0], y[0], label=\"Rule(x)\")\n",
    "plt.title(\"Rule Function\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"rule(x)\")\n",
    "plt.grid(True)\n",
    "plt.legend()\n",
    "plt.show()\n",
    "size = (100, 100)  # 网格大小\n",
    "cca = ContinuousCellularAutomata(size, example_kernel, gol_rule)\n",
    "    # 模拟并可视化\n",
    "cca.simulate(steps=1000, plot_interval=1,dt=0.1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
